<?php
namespace app\api;

use GuzzleHttp;

/**
 * Tr Api 实现
 * @class Trapi
 */
class TrApi
{
    /**
     * 接口后缀地址
     * @var string
     */
    private $api_prefix = '/transmission/rpc';
    /**
     * 接口前缀地址
     */
    private $base_url;
    /**
     * 接口认证session_id
     */
    private $session_id;
    /**
     * 配置参数
     */
    private $config;
    /**
     * login状态
     */
    public $login_status;
    /**
     * guzzle的请求对象
     */
    private $client;

    /**
     * 构造函数
     * @param array $config
     */
    public function __construct($config = [])
    { // config设置全局化
        $this->config = $config;
        // 设置初始接口地址
        $this->base_url = $this->config['port'] ? $this->config['host'] . ':' . $this->config['port'] . '/' : $this->config['host'] . '/';
        // guzzle client对象默认初始化设置
        $this->client = new GuzzleHttp\Client(['base_uri' => $this->base_url, 'http_errors' => false, ['verify' => false, 'timeout' => 10]]);
        $this->initSessionId();
        // $this->getTorrentsInfo('962d7339210750fe9f208ee2896176901a7bc71a');
    }
    public function initSessionId()
    {
        $headers = [
            'Content-Type' => 'application/json',
            'Authorization' => 'Basic ' . base64_encode($this->config['username'] . ':' . $this->config['password']),
        ];
        try {
            $response = $this->client->request('POST', $this->api_prefix, ['headers' => $headers]);
            // 获取到tr的409状态码，说明登录成功保存下
            if ($response->getStatusCode() === 409) {
                // 获取新的会话ID
                $this->session_id = $response->getHeaderLine('X-Transmission-Session-Id');
                $this->login_status = 1;
                return json(['code' => 1, 'msg' => "TR 登录成功"]);
            } else {
                $this->login_status = 0;
                return json(['code' => 0, 'msg' => "账号密码错误"]);
            }
        } catch (\Exception $e) {
            // 捕获任意错误
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }
    }

    public function getTorrentsInfo($hash = '', $filter = '')
    {
        $this->initSessionId();
        $headers = [
            'Authorization' => 'Basic ' . base64_encode($this->config['username'] . ':' . $this->config['password']),
            'X-Transmission-Session-Id' => $this->session_id,
            'Content-Type' => 'json',
        ];

        $body = [
            "method" => "torrent-get",
            "arguments" => [
                "fields" => [
                    "hashString",
                    "name",
                    "downloadDir",
                    "sizeWhenDone",
                    "totalSize",
                    "labels",
                    "id",
                    "error",
                    "errorString",
                    "eta",
                    "isFinished",
                    "isStalled",
                    "leftUntilDone",
                    "metadataPercentComplete",
                    "peersConnected",
                    "peersGettingFromUs",
                    "peersSendingToUs",
                    "percentDone",
                    "queuePosition",
                    "rateDownload",
                    "rateUpload",
                    "recheckProgress",
                    "seedRatioMode",
                    "seedRatioLimit",
                    "status",
                    "trackers",
                    "uploadedEver",
                    "uploadRatio",
                    "webseedsSendingToUs",
                ],
                // "ids" => is_array($hash) ? $hash : [$hash],
            ],
        ];
        $body = json_encode($body);
        $response = $this->client->post($this->api_prefix, [
            'body' => $body,
            'headers' => $headers,
        ]);
        return json_decode($response->getBody()->getContents(), true);
    }
    public function addTorrent($url, $save_path, $is_paused)
    {
        $this->initSessionId();
        $is_paused == 1 ? $is_paused = 'false' : $is_paused = 'true';
        $headers = [
            'Authorization' => 'Basic ' . base64_encode($this->config['username'] . ':' . $this->config['password']),
            'X-Transmission-Session-Id' => $this->session_id,
            'Content-Type' => 'json',
        ];
        $body = [
            "method" => "torrent-add",
            "arguments" => ["paused" => $is_paused, "download-dir" => $save_path, "filename" => $url],
        ];
        $response = $this->client->post($this->api_prefix, [
            'body' => json_encode($body),
            'headers' => $headers,
        ]);
        return json_decode($response->getBody()->getContents(), true);
    }
}
